﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VietThinks.Security;
using System.Configuration;
using Infrastructure;
using VietThinks.Contract;

namespace VietThinks.Website
{
    public static partial class VisitContext
    {
        public static CookieManager Cookie { get { return CookieManager.Instance; } }
        public static SessionManager Session { get { return SessionManager.Instance; } }
        public static ApplicationStateManager Application { get { return ApplicationStateManager.Instance; } }
        public static TransactionManager Transaction { get { return TransactionManager.Instance; } }

        /// <summary>
        /// IUserPrincipal that represents current visitor
        /// </summary>
        public static IUserPrincipal Visitor
        {
            get
            {
                if (VisitContext.Session.Visitor == null)
                {
                    VisitContext.Session.Visitor = ServiceProvider.AuthenticationService.IdentifyVisitor();
                }

                return VisitContext.Session.Visitor;
            }
        }

        /// <summary>
        /// IUserPrincipal that represents current visitor
        /// </summary>
        public static IUserPrincipal Staff
        {
            get
            {
                if (VisitContext.Session.Staff == null)
                {
                    VisitContext.Session.Staff = ServiceProvider.AuthenticationService.IdentifyStaff();
                }

                return VisitContext.Session.Staff;
            }
        }

        public static string OmnitureSessionId
        {
            get
            {
                if (string.IsNullOrEmpty(VisitContext.Session.OmnitureSessionId))
                {
                    VisitContext.Session.OmnitureSessionId = VisitContext.Transaction.CreateSessionId();
                }

                return VisitContext.Session.OmnitureSessionId;
            }
        }

        public static string OmnitureTransactionId
        {
            get
            {
                if (string.IsNullOrEmpty(VisitContext.Session.OmnitureTransactionId))
                {
                    VisitContext.Session.OmnitureTransactionId = VisitContext.Transaction.CreateTransactionId();
                }

                return VisitContext.Session.OmnitureTransactionId;
            }
        }

        public static string CustomerVertical
        {
            get
            {
                if (string.IsNullOrEmpty(VisitContext.Session.CustomerVertical))
                {
                    VisitContext.Session.CustomerVertical = GetCustomerVertical();
                }

                return VisitContext.Session.CustomerVertical;
            }
        }

        public static string CustomerType
        {
            get
            {
                if (string.IsNullOrEmpty(VisitContext.Session.CustomerType))
                {
                    VisitContext.Session.CustomerType = GetCustomerType();
                }

                return VisitContext.Session.CustomerType;
            }
        }

        public static string GetCustomerVertical()
        {
            return "no vertical";
        }

        public static string GetCustomerType()
        {
            var service = ServiceProvider.GetService<ICustomerService>();
            var visitor = VisitContext.Visitor;

            //if (visitor.Identity.IsAuthenticated)
            //{
            //    var defaultContact = service.GetDefaultShippingContact(visitor.UserIdentity.Id);
            //    if (defaultContact != null && defaultContact.Address != null)
            //    {
            //        return defaultContact.Address.Type;
            //    }
            //}

            return string.Empty;
        }

        //public static string GetOrderConfirmationEmail()
        //{
        //    if (!string.IsNullOrEmpty(VisitContext.Session.OrderConfirmationEmail))
        //    {
        //        return VisitContext.Session.OrderConfirmationEmail;
        //    }
        //    if (VisitContext.CheckoutProcess.BillingContact != null)
        //    {
        //        VisitContext.Session.OrderConfirmationEmail = VisitContext.CheckoutProcess.BillingContact.Email;
        //        return VisitContext.Session.OrderConfirmationEmail;
        //    }

        //    return string.Empty;
        //}

        //public static CartManager CartManager
        //{
        //    get
        //    {
        //        CartManager cartManager = VisitContext.Session.CartManager;
        //        if (cartManager == null)
        //        {
        //            VisitContext.Session.CartManager = cartManager = new CartManager();
        //        }
        //        return cartManager;
        //    }
        //}

        //public static CheckoutProcess CheckoutProcess
        //{
        //    get
        //    {
        //        if (VisitContext.Session.CheckoutProcess == null)
        //        {
        //            var service = ServiceProvider.GetService<ICustomerService>();
        //            var checkoutProcess = VisitContext.Session.CheckoutProcess = new CheckoutProcess();
        //            checkoutProcess.ShippingContact = VisitContext.Visitor.UserIdentity.IsAuthenticated ? service.GetDefaultShippingContact(Visitor.UserIdentity.Id) : null;
        //            checkoutProcess.BillingContact = VisitContext.Visitor.UserIdentity.IsAuthenticated ? service.GetDefaultBillingContact(Visitor.UserIdentity.Id) : null;
        //        }

        //        return VisitContext.Session.CheckoutProcess;
        //    }
        //}



        public static void LogInfoActionRequest()
        {
            try
            {
                var context = System.Web.HttpContext.Current;
                string file = context.Server.MapPath("/logs/" + DateTime.Now.ToString("MM-dd-yyyy") + ".txt");
                if (!System.IO.File.Exists(file))
                {
                    using (var fileStream = new System.IO.FileStream(file, System.IO.FileMode.CreateNew))
                    {
                        fileStream.Flush();
                    }
                }
                List<string> contents = new List<string>
                {
                    //1:Date 2:Ip 3:Cookie
                    string.Format("{0}|{1}|{2}",DateTime.Now.ToString("HH:mm:ss"),context.Request.Params["REMOTE_ADDR"],context.Request.Params["HTTP_COOKIE"])
                };
                System.IO.File.AppendAllLines(file, contents.ToArray(), System.Text.Encoding.UTF8);
            }
            catch
            {
            }
        }

        public static CheckoutLogger CheckoutLogger
        {
            get
            {
                CheckoutLogger logger = HttpContext.Current.Items[HttpContext.Current.Session.SessionID] as CheckoutLogger;
                if (logger == null)
                    HttpContext.Current.Items[HttpContext.Current.Session.SessionID] = logger = new CheckoutLogger();
                return logger;
            }
        }
    }

    public class CheckoutLogger
    {
        //List<CheckoutLoggingDto> items = new List<CheckoutLoggingDto>();
        //public void Log(string note)
        //{
        //    Log(note, false);
        //}
        //public void Log(string note, bool isRedirected)
        //{
        //    string LogInfoActionRequest = ConfigurationManager.AppSettings["CheckoutDBLogging"];
        //    if (LogInfoActionRequest.IsEqual("true", true))
        //    {
        //        var Context = HttpContext.Current;
        //        items.Add(new CheckoutLoggingDto
        //        {
        //            ServerType = ConfigurationManager.AppSettings["ServerType"],
        //            GuestId = VisitContext.Cookie.GuestId.ToInt(),
        //            CustomerId = VisitContext.Visitor.Identity.IsAuthenticated ? VisitContext.Visitor.UserIdentity.Id : 0,
        //            SessionId = Context.Session.SessionID,
        //            OmnitureTransactionId = VisitContext.OmnitureTransactionId,
        //            CreatedDate = DateTime.Now,
        //            PreviousURL = Context.Request.Params["HTTP_REFERER"] ?? string.Empty,
        //            RequestURL = Context.Request.RawUrl,
        //            HttpMethod = Context.Request.HttpMethod,
        //            UserAgent = Context.Request.Params["HTTP_USER_AGENT"] ?? string.Empty,
        //            IsRedirected = isRedirected,
        //            Note = note ?? string.Empty,
        //        });
        //    }
        //}
        //public void SaveToDB()
        //{
        //    string LogInfoActionRequest = ConfigurationManager.AppSettings["CheckoutDBLogging"];
        //    if (LogInfoActionRequest.IsEqual("true", true))
        //    {
        //        var service = ServiceProvider.GetService<IAdminService>();
        //        if (items.Count == 0)
        //            Log(string.Empty);
        //        try
        //        {
        //            items.ForEach((dto) =>
        //            {
        //                service.AddCheckoutLog(dto);
        //            });
        //        }
        //        catch { }
        //        finally
        //        {
        //            items.Clear();
        //        }
        //    }
        //}
    }

    public static class TrackingLogin
    {
        public static void Track(string email, System.Web.Mvc.ModelStateDictionary ModelState)
        {
            string errorValidation = string.Empty;
            foreach (var item in ModelState.Where(e => ModelState[e.Key].Errors.Count > 0))
            {
                errorValidation += item.Value.Errors[0].ErrorMessage;
            }
            Track(email, errorValidation);
        }
        public static void Track(string email, string note)
        {
            try
            {
                string trackingLoginStatus = ConfigurationManager.AppSettings["TrackingLoginStatus"];
                if (trackingLoginStatus.IsEqual("true", true))
                {
                    var service = ServiceProvider.GetService<IAdminService>();
                    var Context = HttpContext.Current;
                    //service.TrackingLogin(new TrackingLoginDto
                    //{
                    //    ServerType = ConfigurationManager.AppSettings["ServerType"],
                    //    GuestId = VisitContext.Cookie.GuestId.ToInt(),
                    //    SessionId = Context.Session.SessionID,
                    //    OmnitureTransactionId = VisitContext.OmnitureTransactionId,
                    //    CreatedDate = DateTime.Now,
                    //    PreviousURL = Context.Request.Params["HTTP_REFERER"] ?? string.Empty,
                    //    RequestURL = Context.Request.RawUrl,
                    //    UserAgent = Context.Request.Params["HTTP_USER_AGENT"] ?? string.Empty,
                    //    Note = string.Format("Email: {0}|{1}", email, note ?? string.Empty)
                    //});
                }
            }
            catch { }
        }
    }
}